You write custom CUDA kernels to replace the pytorch operators in the given GeGLU architecture to get speedups.

You have complete freedom to choose the set of operators you want to replace. You may make the decision to replace some operators with custom CUDA kernels and leave others unchanged. You may replace multiple operators with custom implementations, consider operator fusion opportunities (combining multiple operators into a single kernel, for example, combining chunk+gelu+elementwise_mul), or algorithmic changes (such as optimized memory access patterns). You are only limited by your imagination.

Custom CUDA kernel extension via torch.utils.cpp_extension.load_inline

Supervised Contrastive (SupCon) loss computation

Multi-kernel design: normalization + similarity + loss computation

Row-wise L2 normalization with warp-level reduction

Similarity matrix computation via torch::matmul with temperature scaling

Advanced log-sum-exp reduction with warp-shuffle merging

Label-based positive/negative separation for supervised contrastive learning

Warp-shuffle primitives (__shfl_down_sync) for efficient reductions

Two-phase reduction: warp-level → shared memory → final warp

Numerical stability with EPSILON protection

Contiguous tensor handling for memory coalescing



Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is:
import torch
import torch.nn as nn


class Model(nn.Module):
    def __init__(self, temperature):
        super(Model, self).__init__()
        self.temperature = temperature

    def forward(self, features: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
        batch_size = features.shape[0]

        features = torch.nn.functional.normalize(features, dim=1)

        similarity_matrix = torch.matmul(features, features.T) / self.temperature

        mask = labels.unsqueeze(0) == labels.unsqueeze(1)
        mask = mask.float()

        logits_mask = torch.ones_like(mask)
        logits_mask.fill_diagonal_(0)

        exp_logits = torch.exp(similarity_matrix) * logits_mask
        log_prob = similarity_matrix - torch.log(exp_logits.sum(1, keepdim=True))

        mean_log_prob_pos = (mask * log_prob).sum(1) / mask.sum(1)

        loss = -mean_log_prob_pos.mean()

        return loss


batch_size = 16
dim = 128
num_classes = 10


def get_inputs():
    features = torch.randn(batch_size, dim)
    labels = torch.randint(0, num_classes, (batch_size,))
    return [features, labels]


def get_init_inputs():
    temperature = 0.07
    return [temperature]